# -*- coding: utf-8 -*-
"""
Created on Sat Oct 21 00:04:54 2017

@author: Luther
"""

import requests
import re
import time


def getHTMLText(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return '产生异常！'


def getGoodsList(goods_list, text):
    t_list = re.findall(r'\"raw_title\":\".+?\"', text)
    p_list = re.findall(r'\"view_price\":\"\d+?\.\d{2}\"', text)
    l_list = re.findall(r'\"item_loc\":\".+?\"', text)
    s_list = re.findall(r'\"view_sales\":\"\d+?人付款\"', text)
    n_list = re.findall(r'\"nick\":\".+?\"', text)
    for i in range(len(t_list)):
        title = eval(t_list[i].split(':')[1])
        price = eval(p_list[i].split(':')[1])
        loc = eval(l_list[i].split(':')[1])
        sales = eval(s_list[i].split(':')[1])
        nick = eval(n_list[i].split(':')[1])
        goods_list.append('{},{},{},{},{},{}\n'.format(i + 1, title, price,
                                                       loc, sales, nick))
    return goods_list


def saveGoodsList(goods_list):
    with open('D:\\goods_list.csv', 'w') as f:
        f.writelines(goods_list)
    print('指定商品的淘宝信息表已生成，位于D:\\goods_list.csv')


def main():
    url = 'https://s.taobao.com/search?q=' + keyword
    text = getHTMLText(url)
    goods_list = ['序号,商品名称,价格,卖家所在地,最近销量,卖家名称\n']
    goods_list = getGoodsList(goods_list, text)
    saveGoodsList(goods_list)


keyword = input('请输入关键词：')

time1 = time.time()
main()
time2 = time.time()
d_time = time2 - time1
print('共用时{:.2f}s'.format(d_time))
